﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;

namespace S7.Windows.Chat
{
    /// <summary>
    /// Interaction logic for EnterChat.xaml
    /// </summary>
    public partial class EnterChat : Window
    {
        public EnterChat()
        {
            InitializeComponent();
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            M7.ChatClient chat = new M7.ChatClient(tbMessage.Text, Info.GetLocalIP(), Properties.Settings.Default.Port);
            chat.name = "Server";
            ChatServer.ChatMsgs.Add(chat);
            lbChat.Dispatcher.Invoke(new ThreadStart(() =>
                {
                    try
                    {
                        lbChat.ItemsSource = null;
                        lbChat.ItemsSource = ChatServer.ChatMsgs;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                    }
                    
                }),null);
            Thread thr = new Thread(new ThreadStart(() =>
                {
                    ChatServer.SendToClients(chat);
                }));
            thr.IsBackground = true;
            thr.Start();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            lbChat.ItemsSource = ChatServer.ChatMsgs;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Info.enterChatWindow = null;
        }
    }
}
